package com.emprestimoz;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.SimpleCursorAdapter;


public class ListItens extends ListActivity {
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuInflater m = getMenuInflater();
		m.inflate(R.menu.menu, menu);
		return true;
	}
	
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		// TODO Auto-generated method stub
		if(item.getItemId() == R.id.menuCadastrar){
			Intent cadastrarActivity = new Intent(this, EmprestimoZActivity.class);
			startActivity(cadastrarActivity);
		} else if (item.getItemId() == R.id.menuListar) {
			Intent listarActivity = new Intent(this, ListItens.class);
			startActivity(listarActivity);
		}
		return super.onMenuItemSelected(featureId, item);
	}
	
	public void oncreate(Bundle savedInstance){
		DBHelper db = new DBHelper(this, EmprestimoZActivity.EMPRESTIMO, null,EmprestimoZActivity.VERSION);
		StringBuffer query = new StringBuffer();
		query.append("SELECT * FROM item;");
		//db.getWritableDatabase().query(EmprestimoZActivity.TABLE, null, null, null, null, null, null);
		Cursor items = db.getWritableDatabase().rawQuery(query.toString(), null);
		
		items.moveToFirst();
		while (items.moveToNext()) {
			items.getString(items.getColumnIndex("item"));
			
		}
		
		setListAdapter(new SimpleCursorAdapter(ListItens.this, R.layout.listitens, items, new String[]{"item"}, new int[]{R.id.listItens}));
		getListView().setOnItemClickListener(new OnItemClickListener() {
			
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int position,
						long id) {
					// TODO Auto-generated method stub
					Intent listarActivity = new Intent(ListItens.this, EmprestimoZActivity.class);
					listarActivity.putExtra("idItem", getListAdapter().getItemId(position));
					startActivity(listarActivity);
				}
		});
		
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		DBHelper db = new DBHelper(this, EmprestimoZActivity.EMPRESTIMO, null,EmprestimoZActivity.VERSION);
		StringBuffer query = new StringBuffer();
		query.append("SELECT * FROM item;");
		//db.getWritableDatabase().query(EmprestimoZActivity.TABLE, null, null, null, null, null, null);
		Cursor items = db.getWritableDatabase().rawQuery(query.toString(), null);
		
//		items.moveToFirst();
//		while (items.moveToNext()) {
//			items.getString(items.getColumnIndex("item"));
//			
//		}
		
		setListAdapter(new SimpleCursorAdapter(ListItens.this, R.layout.listitens, items, new String[]{"Item"}, new int[]{R.id.listItens}));
	}
	

}
